package cn.i7baozh.cloud.gateway.filter;

import cn.i7baozh.cloud.gateway.predicate.MyOwnRoutePredicateFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.SetPathGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义单独过滤器
 * <p>
 * 仿照 SetPathGatewayFilterFactory 写自定义过滤器
 * 仿照逻辑跟自定义段断言器差不多，要求请求参数必须有我配置的才行
 *  filters:
 *    - MyOwnUrl=axiba
 *  那就是请求参数里必须有axiba才放行
 *
 * @author zhangbaoqi532
 * @date 2024/12/27
 * @see SetPathGatewayFilterFactory
 */
@Component // 必须
public class MyOwnUrlGatewayFilterFactory extends AbstractGatewayFilterFactory<MyOwnUrlGatewayFilterFactory.Config> {

    // 必须有
    public MyOwnUrlGatewayFilterFactory() {
        super(MyOwnUrlGatewayFilterFactory.Config.class);
    }

    /**
     * 这个方法的注释看这里
     * @see MyOwnRoutePredicateFactory#shortcutFieldOrder()
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("template");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

                System.out.println("使用自定义过滤器，配置为：" + config);
                ServerHttpRequest request = exchange.getRequest();
                if (request.getQueryParams().containsKey(config.getTemplate())) {
                    //成功
                    return chain.filter(exchange);
                } else {
                    exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
                    return exchange.getResponse().setComplete();
                }
            }
        };
    }

    public static class Config {
        private String template;

        public String getTemplate() {
            return this.template;
        }

        public void setTemplate(String template) {
            this.template = template;
        }

        @Override
        public String toString() {
            return "Config{" +
                    "template='" + template + '\'' +
                    '}';
        }
    }
}
